<template>
  <div>
    <el-upload
      class="avatar-uploader"
      :action="upload.url"
      :headers="upload.headers"
      name="mf"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  props: {
    url: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      upload: {
        headers: { 'Authorization': getToken() }, // 设置上传的请求头部
        url: process.env.VUE_APP_BASE_API + process.env.VUE_APP_UPLOAD_PATH// 上传的地址
      },
      // 头像路径 回显
      imageUrl: ''
    }
  },
  watch: {
    'url': function(newVal) {
      if (newVal !== '') {
        this.imageUrl = newVal
      }
    }
  },
  methods: {
    // 文件上传成功回调
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.imageUrl = res.msg
      setTimeout(() => {
        this.$emit('loadImageUrl', res.msg)
      }, 0)
    },
    // 文件上传前回调
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg';
      // const isLt2M = file.size / 1024 / 1024 < 2;

      // return file.size / 1024 / 1024 < 2
      return true
    }
  }
}
</script>
<style  scoped>
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

/deep/ .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

/deep/ .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

/deep/ .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
